#!/usr/local/bin/perl

use strict;
use Data::Dumper;
use Cwd;
use lib ("/home/sgetest/lib");
use TIGR::HTCRequest;
use TIGR::HTCUtils;

use Log::Log4perl;

my $log_conf = q~
log4perl.rootLogger=DEBUG, client
log4perl.appender.client=Log::Log4perl::Appender::File
log4perl.appender.client.mode=append
log4perl.appender.client.layout=Log::Log4perl::Layout::PatternLayout
log4perl.appender.client.layout.ConversionPattern=%H [%d{MM/dd HH:mm}] %p %M - %m%n
~;


# setup logging
#
my $logfile = "/usr/local/scratch/$ENV{USER}/arr-job-dir/submit.log";
$log_conf .= "log4perl.appender.client.filename=$logfile\n";
Log::Log4perl::init(\$log_conf);
my $logger = Log::Log4perl->get_logger(__PACKAGE__);
$logger->info("Starting dir array job test.");


# Before starting the test, count the perl processes
my $proc_cnt = TIGR::HTCUtils->get_perl_process_count();
#$logger->info("Active perl process count is : $proc_cnt");
print "Active perl process count is : $proc_cnt \n";
if ($proc_cnt > 20) {
        #print "Active perl process count exceeded max limit of 20. Skipping the launch of new test..\n";
        $logger->info("Active perl process count exceeded max limit of 20. Skipping the launch of new test..");
	TIGR::HTCUtils->log_test_skip("test_htc_dir");
        exit(1);
}

TIGR::HTCUtils->log_test_start("test_htc_dir");
my $request = TIGR::HTCRequest->new(group => "htc-dir",
                                    initialdir => cwd(),
                                    opsys=>"Linux,Solaris");
$request->set_command("/usr/local/scratch/$ENV{USER}/arr-job-dir/test-arr-dir.sh");

# Set the directory for the command to iterate on
$request->add_param({value => "/usr/local/scratch/$ENV{USER}/arr-job-dir/test-dir", type => "DIR"});

$request->set_output("/usr/local/scratch/$ENV{USER}/arr-job-dir/array_test.\$(Index).out");
$request->set_error("/usr/local/scratch/$ENV{USER}/arr-job-dir/array_test.\$(Index).err");

$request->set_getenv(1);

#$request->length('long');


my $id = $request->submit();

my $xx = $request->to_xml();
print $xx;
$request->wait_for_request();

my $message = $request->get_message();
$logger->info("Finished dir array job test. Message: $message");
if($request->get_state() eq "FAILURE") {
    print " Request failed: $message \n";
    exit(1);
} else {
	print Dumper($request->get_tasks());
    print " Request finished with state " . $request->get_state() . " and $message \n";
}
TIGR::HTCUtils->log_test_finish("test_htc_dir");
print "Finished!\n\n";
exit(0);
